var index;

var table;
var form;
var laydate;

$(document).ready(function () {
    $('#page-toolbar-content').show();

    layui.use(['table', 'form', 'laydate'], function () {

        table = layui.table;
        form = layui.form;
        laydate = layui.laydate;
        form.render();

        getAllButton(currUrl).done(function(returnData) {
            createButton(returnData);
            initButtonEvent();
            initDater();
            initTable();
        });

    });

});

function initButtonEvent() {

    var $ = layui.$, active = {

        add: function () {
            loadingChildPage('user_add', '新增用户');
        },
        edit: function () {
            var checkStatus = table.checkStatus('user-table-content');
            var data = checkStatus.data;
            if (data.length <= 0) {
                layer.msg("没有选取任何行！");
            }
            else if (data.length > 1) {
                layer.msg("无法批量修改行！");
            }
            else {
                layer.alert(JSON.stringify(data));
                loadingChildPage('user_edit', '编辑用户');
            }
        },
        del: function () {
            var checkStatus = table.checkStatus('user-table-content');
            var data = checkStatus.data;
            if (data.length <= 0) {
                layer.msg("没有选取任何行！");
            }
            else {
                layer.alert(JSON.stringify(data));
                removeUser(layer);
            }
        },
        role: function() {
            var checkStatus = table.checkStatus('user-table-content');
            var data = checkStatus.data;
            if (data.length <= 0) {
                layer.msg("没有选取任何行！");
            }
            else {
                setUserRole();
            }
        }
    };

    $('.menu-btn-group .layui-btn').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

}


function initDater() {
    laydate.render({
        elem: '#createTime'
    });
}


function initTable() {

    table.render({
        elem: '#user-table-content'
        , url: '../json/testUserData.json'
        , cellMinWidth: 50
        , limit: 15
        , limits: [15]
        , cols: [[
            {type: 'checkbox'}
            , {field: 'userId', width: 70, title: 'ID'}
            , {field: 'username', width: 150, title: '用户名'}
            , {field: 'nickname', width: 150, title: '昵称'}
            , {field: 'sex', width: 60, title: '性别'}
            , {field: 'phone', width: 170, title: '手机号码'}
            , {field: 'email', width: 190, title: '电子邮箱'}
            , {field: 'createTime', width: 170, title: '注册时间'}
            , {field: 'lastLoginTime', width: 170, title: '最后登录时间'}
            , {field: 'lastLoginIp', title: '最后登录IP'}
            , {field: 'status', width: 70, title: '状态'}
            , {field: 'toolbar', width: 240, title: '操作', align: 'center', toolbar: '#tableToolbar'}
        ]]
        , page: {
            layout: ['prev', 'page', 'next', 'skip', 'limit', 'count']
        }
    });

    // 监听工具条
    table.on('tool(page-table)', function (obj) {
        var data = obj.data;
        if (obj.event === 'del') {
            layer.confirm('真的要删除该行吗？', function (index) {
                obj.del();
                layer.close(index);
            });
        } else if (obj.event === 'edit') {
            layer.alert('编辑行：<br>' + JSON.stringify(data))
            loadingChildPage('user_edit', '编辑用户');
        }
        else if (obj.event === 'role') {
            setUserRole();
        }
    });

    $('.layui-table-page').css('text-align', 'right');
    $('.layui-table-page').css('padding-right', '20px');

}

function removeUser() {
    layer.confirm("真的要删除该行吗？");
}

function setUserRole() {

    layui.use('layer', function () {

        var layer = layui.layer;

        index = layer.open({
            title: "设置用户角色",
            type: 1,
            shade: 0,
            area: ['330px', '552px'],
            content:
            '<div style="text-align: center;"></div><div id="user-role-tree" style="padding: 20px;min-height: 400px;max-height: 400px;"></div>' +
            '<hr>' +
            '<div class="layui-form-item" style="text-align: center;margin-bottom: 5px;">' +
            '<button class="layui-btn"><i class="fa fa-check fa-fw" onclick="javascript:layer.close(index);"></i>确认</button>' +
            '<button class="layui-btn layui-btn-danger" onclick="javascript:layer.close(index);"><i class="fa fa-reply fa-fw"></i>返回</button></div></div>'
        });

        getAllRoleTreeData();
    });
}

function getAllRoleTreeData() {

    // 获取所有角色树
    $.ajax({
        type: "POST",
        dataType: "json",
        url: "../json/testUserRoleTreeData.json",
        success: function (returnData) {
            if (returnData.errorCode === 0) {
                createJSTree(returnData.returnJson);
            } else {
                layer.msg("获取角色数据失败");
            }
        }
    });

}

function createJSTree(jsonData) {

    var tree = $('#user-role-tree');

    tree.jstree({
        plugins: ["state", "checkbox", "types"],
        core: {
            multiple: true,
            themes: {
                responsive: !1,
            },
            data: jsonData
        },
        types: {
            default: {
                icon: "fa fa-folder icon-state-warning icon-lg"
            },
            file: {
                icon: "fa fa-file icon-state-warning icon-lg"
            }
        }
    });

    tree.jstree(true).settings.core.data = jsonData;
    tree.jstree(true).refresh();

    tree.jstree(true).get_all_checked = function (full) {
        var tmp = new Array;
        for (var i in this._model.data) {
            if (this.is_undetermined(i) || this.is_checked(i)) {
                tmp.push(full ? this._model.data[i] : i);
            }
        }
        return tmp;
    };

}


